package vn.orderonline.core.dao.common;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;

public abstract class GenericDaoImpl<T, K extends Serializable> extends BaseDao 
										implements GenericDao<T, K>	{
	
	private Class<T> type;
	
	protected Class<T> getType() {
		return this.type;
	}
	
	protected String getClassName() {
		return type.getName();
	}
	
	@SuppressWarnings("unchecked")
	public GenericDaoImpl() {
		Type t = getClass().getGenericSuperclass();
		ParameterizedType pt = (ParameterizedType) t;
		type = (Class<T>) pt.getActualTypeArguments()[0];
	}
	
	public void save(T t) {
		getSession().save(t);
	}
	
	public void delete(T t) {
		getSession().delete(t);
	}
	
	public void update(T t) {
		getSession().update(t);
	}
	
	@SuppressWarnings("unchecked")
	public T find(K id) {
		return (T) getSession().get(type, id);
	}
	
	@SuppressWarnings("unchecked")
	public List<T> findAll() {
		Query query = getSession().createQuery("from " + type.getSimpleName());
		return query.list();
	}
	
	@SuppressWarnings("unchecked")
	public List<T> findByProp(String prop, Object data) {
		Criteria criteria = getSession().createCriteria(type);
		criteria.add(Restrictions.eq(prop, data));
		return criteria.list();
	}
}
